package com.zjw.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class NetUtils {

    private static final int serverPort = 8180;
    private static final int clientPort = 8181;

    public static void udpServer() {
        try (DatagramSocket server = new DatagramSocket(serverPort)) {
            while (true) {
                byte[] buf = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                try {
                    server.receive(packet);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                InetAddress address = packet.getAddress();
                byte[] data = packet.getData();
                System.out.println(address.getHostAddress() + "连接成功！" + new String(data, 0, packet.getLength()));
                udpClient(clientPort, "pang");
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public String getServerIp() {
        try (DatagramSocket server = new DatagramSocket(clientPort)) {
            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            try {
                server.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            InetAddress address = packet.getAddress();
            return address.getHostAddress();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void ping() {
        udpClient(serverPort, "ping");
    }

    private static void udpClient(int port, String msg) {
        try (DatagramSocket socket = new DatagramSocket()) {
            InetAddress localhost = InetAddress.getLocalHost();
            String hostAddress = localhost.getHostAddress();
            hostAddress = hostAddress.substring(0, hostAddress.lastIndexOf(".")) + ".255";
            DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), InetAddress.getByName(hostAddress), port);
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
